package com.vcredit.creditcat.service.loginPreview;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.model.PersonInfo;
import com.vcredit.creditcat.service.PersonInfoService;
import com.vcredit.creditcat.util.RSAUtil;
import com.vcredit.creditcat.vo.CheckBlackParamVo;
import com.vcredit.creditcat.vo.product.hl.HlReturnInfoVo;
import com.vcredit.framework.exception.BaseException;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 还乐登录预检处理类
 * Created by liaoshengjun on 2017/10/27.
 */
@Service("HLPreviewService")
public class HLPreviewService implements IProductPreview{
	@Value("${product.hl.url}")
	private String creditHLUrl;
	// 公钥
	@Value("${xinyongmao.publicKey}")
	private String publicKey;
	// 私钥
	@Value("${xinyongmao.privateKey}")
	private String privateKey;
	//贷前黑名单检查
	@Value("${check.black.url}")
	private String checkBlackUrl;
	@Autowired
	private PersonInfoService personInfoService;

	private static Logger logger = LoggerFactory.getLogger(HLPreviewService.class);
	@Override
	public Integer checkExist(String mobile) throws Exception {
		if(StringUtils.isBlank(mobile)){
			throw new BaseException("调用还乐登录预检失败：手机号为空");
		}
		HlReturnInfoVo authPersonal = null;
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("reginMobile", mobile);
			map.put("productType", "XYM");
			// 加密请求、
			String json = JacksonUtil.Obj2Json(map);
			String code = this.encodeJsonParam(json);
			String resultJson = HttpRequest.doJson(creditHLUrl.concat("check/isCustomerRegisted"), code);
			// 解密数据
			String decodeJsonParam = this.decodeJsonParam(resultJson);
			logger.info("还乐登录预检接口返回："+ decodeJsonParam+"手机号:"+mobile);
			// 转成实体对象
			authPersonal = JacksonUtil.Json2Obj(decodeJsonParam, new TypeReference<HlReturnInfoVo>() {
			});
		} catch (Exception e) {
			logger.error("还乐登录预检接口调用失败",e);
			throw e;
		}
		if(authPersonal!=null && "1".equals(authPersonal.getStatus())){
			if(checkBlack(mobile)){
				return 1;
			}else{
				return 0;
			}
		}else{
			return 0;
		}
	}
	private String encodeJsonParam(String jsonParam) throws UnsupportedEncodingException, Exception {
		// 加密
		String requestContentBase64 = Base64.encodeBase64String(RSAUtil.encryptByPrivateKey(jsonParam.getBytes("utf-8"), this.privateKey));
		return requestContentBase64;
	}

	private String decodeJsonParam(String respJson) throws Exception {
		String result = "";
		// 解密
		byte[] res = RSAUtil.decryptBASE64(respJson);
		result = new String(RSAUtil.decryptByPublicKey(res, this.publicKey));
		return result;
	}

	private boolean checkBlack(String mobile)throws Exception {
		boolean result;
		PersonInfo personParam=new PersonInfo();
		personParam.setPersonPhone(mobile);
		List<PersonInfo> personInfoList = personInfoService.find(personParam);
		if(personInfoList ==null || personInfoList.size()==0){
			return true;
		}
		CheckBlackParamVo checkBlackParamVo=new CheckBlackParamVo();
		checkBlackParamVo.setProjectTeam("信用猫");
		checkBlackParamVo.setProductName("LOANKIND/HUANLE");
		checkBlackParamVo.setIdentityNo(personInfoList.get(0).getPersonIdeno());
		checkBlackParamVo.setName(personInfoList.get(0).getPersonName());
		checkBlackParamVo.setAction("300");
		checkBlackParamVo.setMobile(mobile);
		try{
			String resultJson =HttpRequest.doJson(checkBlackUrl, JacksonUtil.Obj2Json(checkBlackParamVo));
			logger.info("还乐登录黑名单检查接口返回："+ resultJson+"手机号:"+mobile);
			Map<String,Object> resultMap=JacksonUtil.Json2Map(resultJson);
			if(resultMap.get("Status")!=null){
				Integer status=(Integer) resultMap.get("Status");
				if(status.equals(1)){
					Map<String,Object> contentMap=JacksonUtil.Json2Map(resultMap.get("Content").toString());
					Integer black=(Integer)contentMap.get("IsBlackUser");
					if(black.equals(1)){
						result=false;
					}else{
						result=true;
					}
				}else if(status.equals(0)){
					result=true;
				}else{
					throw new BaseException("还乐登录黑名单检查接口调用异常"+"手机号:"+mobile);
				}
			}else{
				throw new BaseException("还乐登录黑名单检查接口调用异常"+"手机号:"+mobile);
			}
			return result;
		}catch (Exception e){
			logger.error("还乐登录黑名单检查接口调用失败"+"手机号:"+mobile,e);
			throw e;
		}
	}
}
